package com.ceba.test.base.language;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;


import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import configs.context.ResourceContext;

/*
 * 获取资源文件内容
 */
public final class ResourceUtils {
	static Logger logger = LoggerFactory.getLogger(ResourceUtils.class);

	private final static String MESSAGES_CONFIG="i18n/messages_config.txt";
	private static String messages_config_json;
	
	/**
	 * 获取资源文件对应内容
	 * 参数分别是 resourceName 对应名称 ,keys 对应 {0},{1}
	 * @param resourceName
	 * @param keys
	 * @return
	 */
	public static String getMessage(String resourceName,Object[]keys){
		return ResourceContext.getMessage(resourceName,keys);
	}
	
	/**
	 * 获取资源文件对应内容
	 * 参数分别是 resourceName 对应名称 ,keys 对应 {0},{1}
	 * @param resourceName
	 * @param keys
	 * @return
	 */
	public static String getMessage(String resourceName){
		return ResourceContext.getMessage(resourceName);
	}
	
	
	public static String getMessageConfig(){
		if(StringUtils.isEmpty(messages_config_json)){
			String path=ResourceUtils.class.getResource("/").getPath()+MESSAGES_CONFIG;
			try {
				messages_config_json=FileUtils.readFileToString(new File(path),"utf-8");
			} catch (IOException e) {
				messages_config_json="[{\"country\":\"简\",\"language\":\"zh_CN\"},{\"country\":\"繁\",\"language\":\"zh_TW\"},{\"country\":\"En\",\"language\":\"en_US\"}]";
				logger.debug(e.getMessage());
			}
		}
		return messages_config_json;
	}
	

	
	private static String getMessage(String key,Object[] fmargs, Locale locale) {
		ResourceBundle resourceBundle = null;
		if(locale.getLanguage().equals(Locale.ENGLISH.getLanguage())){
			resourceBundle = ResourceBundle.getBundle("i18n.messages_en_US", locale);
		}else{
			resourceBundle = ResourceBundle.getBundle("i18n.messages", locale);
		}
		String msg = resourceBundle.getString(key);
		if (resourceBundle.containsKey(key)) {
			if ((fmargs != null && fmargs.length ==0) || fmargs == null) {
				return msg;
			}
		}
		
		return MessageFormat.format(msg, fmargs);
	}
	
}
